package com.rytong.tools.ui;

import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

/**
 * @author zhou.yang
 * @Description 开关控件，需要以下几个xml资源文件 switchleft_bg.xml, switchoff_bg.xml, switchon_bg.xml, switchright_bg.xml
 */
@SuppressWarnings("deprecation")
public class LPSwitchCopy extends Component {
    // 存储控件的value属性
    private HashMap<String, String> hashForValue_;

    private boolean isChecked_;
    
    public Bitmap checkedBg_;
    public Bitmap unCheckedBg_;

    public class MyLPSwitch extends View implements CompositedComponent {

        public MyLPSwitch(Context context) {
            super(context);
            hashForValue_ = new HashMap<String, String>();
        }

        @Override
        public Component composited() {
            return LPSwitchCopy.this;
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
        	super.onDraw(canvas);
        	if(unCheckedBg_ != null && !unCheckedBg_.isRecycled()
        			&& checkedBg_ != null && !checkedBg_.isRecycled()){
        		String str=getPropertyByName("checked");
        		if(!str.equals(""))
        		{
                  if(str.equals("true")){
        		    isChecked_=true;
        		}else{
        			isChecked_=false;	
        		}
        	   if (isChecked_) {
        	            setPropertyByName("checked", "true");
        	            setPropertyByName("value", hashForValue_.get("true"));
        	        } else {
        	            setPropertyByName("checked", "false");
        	            setPropertyByName("value", hashForValue_.get("false"));
        	        }
        		} 
        		if (!isChecked_) {
        		    canvas.drawBitmap(unCheckedBg_, 0, 0, getPaint());
        		} else {
        		    canvas.drawBitmap(checkedBg_, 0, 0, getPaint());
        		}
       	}
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int touchEvent = event.getAction();
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                xDown_ = event.getX();
                yDown_ = event.getY();
                return true;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                // 预防控件出现连击效果
                long currentTime = System.currentTimeMillis();
                long timedifference = currentTime - LASTCLICKTIME;
                if (timedifference < 0) {
                    LASTCLICKTIME = currentTime;
                } else if (timedifference < jetLag_) {
                    LASTCLICKTIME = currentTime;
                    return false;
                } else {
                    LASTCLICKTIME = currentTime;
                }

                xUp_ = (int) event.getX();
                yUp_ = (int) event.getY();
                // 如果x或者y方向移动小于VALUE_个像素才判断为点击弹起，如果大于VALUE_个像素则判断为移动，不执行弹起效�
                if (Math.abs(xUp_ - xDown_) > offset_ || Math.abs(yUp_ - yDown_) > offset_) {
                    return false;
                }
                setChecked();
                // 设置segment的lua点击事件
                onClick((String) composited().property_.get("onclick"));
                break;
            }
            return super.onTouchEvent(event);
        }

    }

    @Override
    public void initRealView(Activity arg0, String arg1) {
        realView_ = new MyLPSwitch(arg0);
    }

    @Override
    public void mouldH() throws Exception {
        super.mouldH();
        // 设置选中项
        String checked = (String) property_.get("checked");
        if (checked != null && checked.equalsIgnoreCase("true")) {
            hashForValue_.put("true", getPropertyByName("value"));
            isChecked_ = true;
            setValueToP("true", getPropertyByName("value"));
        } else {
            hashForValue_.put("false", getPropertyByName("value"));
            isChecked_ = false;
            setValueToP("false", getPropertyByName("value"));
            setPropertyByName("checked", "false");
        }
        setSwitchIcons();
        realView_.postInvalidate();
    }
    
    /**
     * 设置value属性给前一个switch控件
     * 
     * @param string
     * @param propertyByName
     */
    private void setValueToP(String key, String value) {
        // TODO Auto-generated method stub
        LPLayout temp = (LPLayout) getParent();
        if (null != temp) {
            Component comp;
            int index = temp.indexOfChild(realView_);
            index = index - 1;
            // 如果index<0，表示该控件为其父控件的第一个控件，不需要进行删除操作
            if (index < 0)
                return;
            comp = temp.getChildAt(index); // 拿前一个switch控件。
            if ((getPropertyByName("name").equalsIgnoreCase(comp.getPropertyByName("name")) 
                    && (comp instanceof LPSwitchCopy))) {
                // 如果上个控件为lpswitch控件，且名字属性相同，说明是处于同一组的。则将value属性传递给上一个控件
                LPSwitchCopy lpsc = (LPSwitchCopy) comp;
                lpsc.hashForValue_.put(key, value);
                temp.removeView(this);
            }
        }
    }


    /**
     * 更改选中状态
     * */
    protected void setChecked() {
        if (isChecked_)
            isChecked_ = false;
        else
            isChecked_ = true;
        
        if (isChecked_) {
            setPropertyByName("checked", "true");
            setPropertyByName("value", hashForValue_.get("true"));
        } else {
            setPropertyByName("checked", "false");
            setPropertyByName("value", hashForValue_.get("false"));
        }
        
        changeValueForOther();
        realView_.postInvalidate();
    }
    
    public boolean isChecked() {
    	return isChecked_;
    }
    
    /**
     * 设置背景图
     * */
    public void setSwitchIcons(){
        if (null != realView_) {
        	if(checkedBg_ == null || unCheckedBg_ == null){
        		if(getContext() != null){
        		    checkedBg_ = Utils.getBitmapFromResources(getContext(), "switch_yes.png");
        		    unCheckedBg_ = Utils.getBitmapFromResources(getContext(), "switch_no.png");
        		}            
        	}
        	if(checkedBg_ != null && unCheckedBg_ != null){
        		checkedBg_ = Bitmap.createScaledBitmap(checkedBg_, width_, height_, true);
        		unCheckedBg_ = Bitmap.createScaledBitmap(unCheckedBg_, width_, height_, true);
        	}
        }
        realView_.postInvalidate();
    }
    
    /**
     * 设置隐藏的switch  属性值
     * */
    private void changeValueForOther(){
        int size = Component.VWIDGETARRAY.size();
        Object o = null;
        Component view;
        for (int i = 0; i < size; i++) {
            o = Component.VWIDGETARRAY.get(i);
            if (null == o)
                continue;
            if (o instanceof Component) {
                view = (Component) o;
                // 同组的其他switch。
                if(getPropertyByName("name").equalsIgnoreCase(view.getPropertyByName("name"))
                		&& (view instanceof LPSwitchCopy) && view != this){
                    if(isChecked_){//当前为选中时，另一个为未选中
                        view.setPropertyByName("checked", "false");
                        ((LPSwitchCopy) view).isChecked_ = false;
                    } else {
                        view.setPropertyByName("checked", "true");
                        ((LPSwitchCopy) view).isChecked_ = true;
                    }
                }
            }
        }
    }
    
    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	if(hashForValue_ != null){
    		hashForValue_.clear();
    		hashForValue_ = null;
    	}
    	Utils.releaseObject(checkedBg_);
    	Utils.releaseObject(unCheckedBg_);
    }
}
